package com.xhwl.centiotdata.pushtrigger.security;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.service.cent.IBiEnvCentService;
import com.xhwl.centiotdata.service.cent.ICentSecurityService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.common.constant.cent.bi.TimeGrainConstant;
import com.xhwl.common.dto.cent.bi.OdsTrafficLimitMetricsDTO;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.device.iot.DeviceService;
import com.xhwl.common.dto.cent.device.iot.DeviceServiceBody;
import com.xhwl.common.dto.cent.device.iot.IotDeviceJson;
import com.xhwl.common.dto.cent.device.iot.IotPassengerFlowStatistics;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.utils.LocalDateTimeUtils;
import com.xhwl.common.vo.cent.security.CrowdDegreeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 9:41 2022/1/25
 */
@Slf4j
@RequestMapping("/")
@RestController
public class PassengerFlowController {

    @Autowired
    private IDeviceCentService deviceCentService;

    @Autowired
    private ICentSecurityService centSecurityService;
    @Autowired
    private IBiEnvCentService iBiEnvCentService;

    /**
     * /iot-passenger-flow/statistics/2/1/2
     * @param data
     * @param projectId
     * @param productId
     */
    @PostMapping("/iot-passenger-flow/statistics/{projectId}/{productId}/{deviceTypeId}")
    public void passengerFlowStatistics(@RequestBody IotDeviceJson<DeviceServiceBody<IotPassengerFlowStatistics>> data,
                                        @PathVariable Integer projectId, @PathVariable Integer productId,
                                        @PathVariable Integer deviceTypeId) {
        log.info("======华为IoTdata海康人脸拥挤度统计开始=======");
        ResultJson resultJson = centSecurityService.crowdingDegreeList(projectId);
        List<DeviceService<IotPassengerFlowStatistics>> services = data.getNotify_data().getBody().getServices();
        String deviceId = data.getNotify_data().getHeader().getDevice_id();
        DevicePageQuery devicePageQuery = new DevicePageQuery();
        devicePageQuery.setProjectId(projectId);
        devicePageQuery.setProductId(productId);
        devicePageQuery.setIotDeviceId(deviceId);
        devicePageQuery.setDeviceTypeId(deviceTypeId);
        Page<DeviceDTO> devicePage = deviceCentService.pageDevice(null, devicePageQuery);
        DeviceDTO deviceDTO = Optional.ofNullable(devicePage).map(Page::getRecords)
                .map(r -> r.stream().filter(d -> d.getIotDeviceId().equals(deviceId)).findAny()
                        .orElseThrow(() -> new RuntimeException("未匹配到设备中台设备"))).get();
        Integer limit = Optional.ofNullable(resultJson)
                .map(ResultJson::getResult)
                .map(o -> JSONObject.parseArray(o.toString(), CrowdDegreeVO.class))
                .map(o -> o.stream().collect(Collectors.toMap(CrowdDegreeVO::getThirdDeviceId, CrowdDegreeVO::getTrafficLimit, (key1, key2) -> key2)))
                .map(m -> m.get(deviceId))
                .orElse(100);
        Integer id = deviceDTO.getId();
        // 1.同步设备数据到配置
        centSecurityService.syncCrowdingDegree(deviceDTO);
        // 2.统计
        List<OdsTrafficLimitMetricsDTO> list = new ArrayList<>();
        for (DeviceService<IotPassengerFlowStatistics> service : services) {
            IotPassengerFlowStatistics properties = service.getProperties();
            LocalDateTime statisticsTime = properties.getStatisticsTime();
            String dt = LocalDateTimeUtils.formatTime(statisticsTime, LocalDateTimeUtils.DATE_MIN);
            OdsTrafficLimitMetricsDTO dto = new OdsTrafficLimitMetricsDTO();
            dto.setProjectId(projectId);
            dto.setDeviceId(id);
            dto.setThirdDeviceId(deviceId);
            dto.setOrgId(deviceDTO.getOrganizationId());
            dto.setUpdateTime(LocalDateTime.now());
            dto.setDt(dt);
            dto.setTimeGrain(TimeGrainConstant.MIN);
            dto.setPass(properties.getPass());
            dto.setLimit(limit);
            list.add(dto);
        }
        iBiEnvCentService.syncTrafficLimit(JSONObject.toJSONString(list));
        log.info("======华为IoTdata海康人脸拥挤度统计结束=======");
    }
}
